package cn.zebra.dev.admin.module.delivery.controller;

import cn.zebra.dev.admin.module.delivery.dto.DeliveryDTO;
import cn.zebra.dev.admin.module.delivery.dto.DeliveryItemDTO;
import cn.zebra.dev.admin.module.delivery.dto.DeliveryListDTO;
import cn.zebra.dev.admin.module.delivery.vo.DeliveryItemVO;
import cn.zebra.dev.admin.module.delivery.vo.DeliveryVO;
import cn.zebra.dev.admin.module.login.SecurityAdminService;
import cn.zebra.dev.common.constant.ParamsConstant;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.shop.module.delivery.entity.DeliveryEntity;
import cn.zebra.dev.shop.module.delivery.entity.DeliveryItemEntity;
import cn.zebra.dev.shop.module.delivery.service.DeliveryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * @author runnable@sina.cn
 */
@Api(tags = "运费管理")
@RequestMapping("/delivery")
@RestController
public class DeliveryController {

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private SecurityAdminService adminService;

    @GetMapping("/list")
    @ApiOperation("运费模板列表")
    public Result<PageUtils<DeliveryListDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> map = new HashMap<>(2);
        map.put(ParamsConstant.LIMIT, limit);
        map.put(ParamsConstant.PAGE, page);
        PageUtils<DeliveryEntity> pageUtils = deliveryService.findPage(map);
        PageUtils<DeliveryListDTO> data = new PageUtils<>();
        List<DeliveryEntity> list = pageUtils.getList();
        if (list.size() > 0) {
            List<DeliveryListDTO> dtoList = new LinkedList<>();
            list.forEach(entity -> {
                DeliveryListDTO dto = new DeliveryListDTO();
                BeanUtils.copyProperties(entity, dto);
                dtoList.add(dto);
            });
            data.setList(dtoList);
        }
        return Result.success(data);
    }

    @GetMapping("/get/{id}")
    @ApiOperation("获取运费模板信息")
    public Result<DeliveryDTO> get(@PathVariable Long id) {
        DeliveryEntity entity = deliveryService.findById(id);
        DeliveryDTO dto = new DeliveryDTO();
        BeanUtils.copyProperties(entity, dto);
        List<DeliveryItemDTO> itemDTOList = new LinkedList<>();
        entity.getItemList().forEach(itemEntity -> {
            DeliveryItemDTO itemDTO = new DeliveryItemDTO();
            BeanUtils.copyProperties(itemEntity, itemDTO);
            itemDTOList.add(itemDTO);
        });
        dto.setItemList(itemDTOList);
        return Result.success(dto);
    }

    @PostMapping("/save")
    @ApiOperation("保存运费模板")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody @Valid DeliveryVO vo) {
        DeliveryEntity entity = convertEntity(vo);
        if (!deliveryService.saveDelivery(entity, adminService.getId())) {
            throw new RuntimeException("添加失败!");
        }
        return Result.success("添加成功!");
    }

    @PostMapping("/update/{id}")
    @ApiOperation("修改运费模板")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@PathVariable Long id, @RequestBody @Valid DeliveryVO vo) {
        DeliveryEntity entity = convertEntity(vo);
        if (!deliveryService.updateDelivery(id, entity, adminService.getId())) {
            throw new RuntimeException("修改失败!");
        }
        return Result.success("修改成功!");
    }

    private DeliveryEntity convertEntity(DeliveryVO vo) {
        DeliveryEntity entity = new DeliveryEntity();
        BeanUtils.copyProperties(vo, entity);
        Collection<DeliveryItemVO> itemList = vo.getItemList();
        List<DeliveryItemEntity> itemEntities = new LinkedList<>();
        itemList.forEach(itemDTO -> {
            DeliveryItemEntity itemEntity = new DeliveryItemEntity();
            BeanUtils.copyProperties(itemDTO, itemEntity);
            itemEntities.add(itemEntity);
        });
        entity.setItemList(itemEntities);
        return entity;
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("删除运费模板")
    public Result delete(@PathVariable Long id) {
        DeliveryEntity entity = new DeliveryEntity();
        entity.setDeleteFlag(true);
        if (deliveryService.update(entity, "id = {0}", id)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败!");
    }
}
